package com.fzk.blog.settings.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.tokenizer.engine.mynlp.MynlpResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fzk.blog.bean.User;
import com.fzk.blog.bean.vo.UserInfo;
import com.fzk.blog.exception.MyException;
import com.fzk.blog.settings.service.IUserService;
import com.fzk.blog.utils.MyRegexUtil;
import com.fzk.blog.utils.ResponseResult;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author fzk
 * @date 2021-08-15 16:38
 */
@RestController
public class UserController {
    @Resource
    private IUserService userService;

    @PostMapping(path = "/user/login")
    public Map<String, Object> login(
            @RequestParam("phone") String phone,
            @RequestParam("password") String password
    ) throws JsonProcessingException {
        // 1.参数检查
        checkArgs(phone, password);

        // 2.调用service层
        return userService.doLogin(phone, password);
    }


    @PostMapping(path = "/user/register")
    public Map<String, Object> register(
            @RequestParam("phone") String phone,
            @RequestParam("email") String email,
            @RequestParam("password") String password,
            @RequestParam("code") String code,
            @RequestParam("role_id") int roleId
    ) throws JsonProcessingException {
        // 1.检查参数
        if (!MyRegexUtil.phone_match(phone))
            return ResponseResult.error(400, "手机号格式不正确：" + phone);
        if (!MyRegexUtil.email_match(email))
            return ResponseResult.error(400, "邮箱格式不正确：" + email);
        if (!MyRegexUtil.password_match(password))
            return ResponseResult.error(400, "密码至少8位");
        if (code == null || code.length() == 0)
            return ResponseResult.error(400, "请提供验证码");

        // 2.调用service层
        return userService.doRegister(phone, email, password, code, roleId);
    }

    @GetMapping(path = "/user/sendCode")
    public Map<String, Object> sendCode(
            @RequestParam("email") String email
    ) {
        // 1.检查参数
        if (!MyRegexUtil.email_match(email))
            return ResponseResult.error(400, "邮箱格式不正确：" + email);
        // 2.调service
        return userService.sendCode(email);
    }

    @GetMapping(path = "/user/forgetPassword")
    public Map<String, Object> sendCode(
            @RequestParam("phone") String phone,
            @RequestParam("email") String email
    ) {
        // 1.检查参数
        if (!MyRegexUtil.phone_match(phone))
            return ResponseResult.error(400, "手机号格式不正确：" + phone);
        if (!MyRegexUtil.email_match(email))
            return ResponseResult.error(400, "邮箱格式不正确：" + email);

        // 2.调service层
        return userService.sendCode(phone, email);
    }

    @PostMapping(path = "/user/forgetPassword")
    public Map<String, Object> forgetPassword(
            @RequestParam("phone") String phone,
            @RequestParam("email") String email,
            @RequestParam("password") String password,
            @RequestParam("code") String code
    ) throws JsonProcessingException {
        // 1.检查参数
        checkArgs(phone, email, password, code);

        // 2.调service层
        return userService.doForgetPwd(phone, email, password, code);
    }

    @GetMapping(path = "/user/myInfo")
    @SaCheckLogin// 检查登录
    public Map<String, Object> getMyInfo() throws InterruptedException, JsonProcessingException {
        Thread.sleep(200);//刻意休眠0.2s
        // 1.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 2.调用service层
        UserInfo userInfo = userService.getMyInfo(loginId);

        // 3.返回数据
        return ResponseResult.success("查询成功", userInfo);
    }

    @PutMapping(path = "/user/myInfo")
    @SaCheckLogin//检查登录
    public Map<String, Object> updateMyInfo(
            @RequestParam("username") String username,
            @RequestParam("head_portrait_url") String headPortraitUrl,
            @RequestParam("address") String address,
            @RequestParam("sex") String sex
            //@RequestParam(name = "phone", required = false) String phone
    ) {
        // 1.参数检查
        checkArgs(username, headPortraitUrl, address, sex);

        // 2.获取loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 3.装参数
        User user = new User();
        user.setId(loginId);
        user.setUsername(username);
        user.setHeadPortraitUrl(headPortraitUrl);
        user.setAddress(address);
        user.setSex(sex);

        // 4.调用service
        return userService.updateMyInfo(loginId, user);
    }

    @PutMapping(path = "/user/resetPwd")
    @SaCheckLogin//检查登录
    public Map<String, Object> resetPwd(
            @RequestParam("password") String newPassword
    ) {

        // 1.获取loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 2.调用service
        userService.resetPwd(loginId, newPassword);

        // 3.返回结果
        return ResponseResult.success("修改成功");
    }


    @PostMapping(path = "/user")
    @SaCheckRole("root")//检查角色
    public Map<String, Object> insertUser(
            @RequestParam(name = "phone") String phone,
            @RequestParam(name = "username") String username,
            @RequestParam(name = "password") String password,
            @RequestParam(name = "role_id") String role_id,
            @RequestParam(name = "address") String address,
            @RequestParam(name = "sex") String sex,
            @RequestParam(name = "email") String email,
            @RequestParam(name = "head_portrait_url") String headPortraitUrl
    ) throws JsonProcessingException {
        // 1.参数检查
        checkArgs(phone, username, password, role_id, address, sex, email, headPortraitUrl);
        // 1.2.检查phone和email
        if (!MyRegexUtil.phone_match(phone))
            return ResponseResult.error(400, "手机号格式不正确：" + phone);
        if (!MyRegexUtil.email_match(email))
            return ResponseResult.error(400, "邮箱格式不正确：" + email);

        // 2.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 3.装入参数：password交给service层
        User user = new User();
        user.setPhone(phone);
        user.setUsername(username);
        user.setRoleId(Integer.parseInt(role_id));
        user.setAddress(address);
        user.setSex(sex);
        user.setEmail(email);
        user.setEmailFlag(true);
        user.setHeadPortraitUrl(headPortraitUrl);

        // 4.调用service层
        return userService.insertUser(user, password, loginId);
    }

    @PutMapping(path = "/user")
    @SaCheckRole("root")//检查角色
    public Map<String, Object> updateUser(
            @RequestParam("id") int userId,
            //@RequestParam("phone") String phone,目前不能修改phone
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("role_id") String role_id,
            @RequestParam("address") String address,
            @RequestParam("sex") String sex,
            // @RequestParam("email") String email,
            @RequestParam("head_portrait_url") String headPortraitUrl
    ) {
        // 1.参数检查
        checkArgs(username, password, role_id, address, sex, headPortraitUrl);

        // 2.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 3.装入参数：password交给service层
        User user = new User();
        user.setId(userId);
        user.setUsername(username);
        user.setRoleId(Integer.parseInt(role_id));
        user.setAddress(address);
        user.setSex(sex);
        user.setHeadPortraitUrl(headPortraitUrl);

        // 4.调用service层
        UserInfo userInfo = userService.updateUser(user, password, loginId);

        return ResponseResult.success("修改成功", userInfo);
    }

    @DeleteMapping(path = "/user")//仅删除用户，不删除博客和评论
    @SaCheckRole("root")
    public Map<String, Object> deleteUsers(
            @RequestParam("ids") int[] ids
    ) {
        // 1.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 2.调用service
        int i = userService.deleteUsers(ids, loginId);

        return ResponseResult.success("成功删除用户数：" + i + "    注意的是：并没有删除博客和评论哦");
    }


    @GetMapping(path = "/user/info")
    @SaCheckRole("root")//检查角色
    public Map<String, Object> getUserInfoListOrOne(
            @RequestParam(name = "id", required = false) String id,
            @RequestParam(name = "phone", required = false) String phone,
            @RequestParam(name = "username", required = false) String username,
            @RequestParam(name = "blog_number_min", required = false) String blogNumberMin,
            @RequestParam(name = "blog_number_max", required = false) String blogNumberMax,
            @RequestParam(name = "page_no", required = false) String pageNo,
            @RequestParam(name = "page_size", required = false) String pageSize
    ) throws JsonProcessingException {
        // 1. 检查id
        if (id == null) {
            // 2.1 查询userInfo的列表
            List<UserInfo> userInfoList = null;
            // 判断是否是分页查询
            if (pageNo == null && pageSize == null)// 2.1.1 查询所有
            {
                userInfoList = userService.getUserInfoList();
                return ResponseResult.success("查询成功", userInfoList);
            } else if (Strings.trimToNull(pageNo) == null || Strings.trimToNull(pageSize) == null)
                throw new MyException(400, "参数错误：page_no:" + pageNo + ";page_size:" + pageSize);
            else // 2.1.2 分页查询
            {
                if (Strings.trimToNull(phone) == null)
                    phone = "";
                if (Strings.trimToNull(username) == null)
                    username = "";
                if (Strings.trimToNull(blogNumberMin) == null)
                    blogNumberMin = "0";
                if (Strings.trimToNull(blogNumberMax) == null)
                    blogNumberMax = Integer.MAX_VALUE + "";
                int page_no = Integer.parseInt(pageNo);
                int page_size = Integer.parseInt(pageSize);
                int index = (page_no - 1) * page_size;
                Map<String, Object> returnMap = userService.
                        getUserInfoListPage(phone, username,
                                Integer.parseInt(blogNumberMin),
                                Integer.parseInt(blogNumberMax),
                                index, page_size);

                returnMap.put("code", 200);
                returnMap.put("msg", "查询成功");
                return returnMap;
            }
        } else if (Strings.trimToNull(id) == null)
            throw new MyException(400, "参数错误：id：" + id);
        else {
            // 2.2 查询特定userInfo
            UserInfo userInfo = userService.getUserInfoById(Integer.parseInt(id));
            return ResponseResult.success("查询成功", userInfo);
        }
    }

    @GetMapping(path = "/user/infoWithPwd")
    @SaCheckRole("root")//检查角色
    public Map<String, Object> getUserInfoWithPwd(
            @RequestParam("id") int userId
    ) {
        UserInfo userInfo = userService.getUserInfoWithPwd(userId);
        return ResponseResult.success("查询成功", userInfo);
    }

    /**
     * 参数检查
     *
     * @param args 可变形参
     */
    private void checkArgs(String... args) {
        for (String arg : args) {
            if (arg == null || arg.length() == 0)
                throw new MyException(400, "参数错误：" + arg);
        }
    }

}
